package com.yupi.yupicturebackend.manager;

import com.yupi.yupicturebackend.model.dto.picture.*;
import com.yupi.yupicturebackend.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 图片增强功能管理器
 * 
 * <p>整合所有图片处理扩展功能的统一入口</p>
 * 
 * @author yupi
 */
@Slf4j
@Component
public class PictureEnhancementManager {

    /**
     * 智能分析图片
     *
     * @param imageUrl 图片URL
     * @return 分析结果
     */
    public PictureAnalysisResult intelligentAnalysis(String imageUrl) {
        try {
            PictureAnalysisResult result = PictureAnalysisUtils.analyzeQuality(imageUrl);
            
            // 异步执行其他分析任务
            CompletableFuture<PictureColorInfo> colorAnalysis = CompletableFuture
                .supplyAsync(() -> PictureAnalysisUtils.analyzeColors(imageUrl));
            
            CompletableFuture<List<String>> tagGeneration = CompletableFuture
                .supplyAsync(() -> PictureAnalysisUtils.generateTags(imageUrl));
            
            CompletableFuture<String> textExtraction = CompletableFuture
                .supplyAsync(() -> PictureAnalysisUtils.extractText(imageUrl));
            
            CompletableFuture<List<String>> objectDetection = CompletableFuture
                .supplyAsync(() -> PictureAnalysisUtils.detectObjects(imageUrl));
            
            // 等待所有任务完成
            CompletableFuture.allOf(colorAnalysis, tagGeneration, textExtraction, objectDetection)
                .join();
            
            // 整合结果
            result.setColorInfo(colorAnalysis.join());
            result.setGeneratedTags(tagGeneration.join());
            result.setExtractedText(textExtraction.join());
            result.setDetectedObjects(objectDetection.join());
            result.setAnalysisTimestamp(System.currentTimeMillis());
            
            return result;
            
        } catch (Exception e) {
            log.error("智能分析图片失败: {}", imageUrl, e);
            return new PictureAnalysisResult();
        }
    }

    /**
     * 智能水印处理
     *
     * @param imageUrl 图片URL
     * @param watermarkConfig 水印配置
     * @param copyrightInfo 版权信息
     * @return 处理结果
     */
    public Map<String, Object> intelligentWatermark(String imageUrl, WatermarkConfig watermarkConfig, CopyrightInfo copyrightInfo) {
        Map<String, Object> result = new java.util.HashMap<>();
        
        try {
            // 添加可见水印
            byte[] visibleWatermark = null;
            if ("text".equals(watermarkConfig.getType())) {
                visibleWatermark = PictureWatermarkUtils.addTextWatermark(imageUrl, watermarkConfig);
            } else if ("image".equals(watermarkConfig.getType())) {
                visibleWatermark = PictureWatermarkUtils.addImageWatermark(imageUrl, 
                    watermarkConfig.getWatermarkImageUrl(), watermarkConfig);
            }
            
            // 添加隐形水印
            byte[] invisibleWatermark = PictureWatermarkUtils.addInvisibleWatermark(imageUrl, copyrightInfo);
            
            // 生成图片指纹
            String fingerprint = PictureWatermarkUtils.generateImageFingerprint(imageUrl);
            
            result.put("visibleWatermark", visibleWatermark);
            result.put("invisibleWatermark", invisibleWatermark);
            result.put("fingerprint", fingerprint);
            result.put("success", true);
            
        } catch (Exception e) {
            log.error("智能水印处理失败: {}", imageUrl, e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 一键社交分享
     *
     * @param shareConfig 分享配置
     * @param platforms 目标平台列表
     * @return 分享结果
     */
    public Map<String, Object> oneClickShare(ShareConfig shareConfig, List<SocialPlatform> platforms) {
        Map<String, Object> result = new java.util.HashMap<>();
        
        try {
            // 生成多平台分享链接
            Map<SocialPlatform, String> shareUrls = PictureSocialShareUtils
                .generateMultiPlatformShareUrls(platforms, shareConfig);
            
            // 生成短链接
            String shortUrl = PictureSocialShareUtils.generateShortUrl(shareConfig.getUrl());
            
            // 生成分享海报
            SharePosterConfig posterConfig = createDefaultPosterConfig(shareConfig);
            byte[] poster = PictureSocialShareUtils.generateSharePoster(posterConfig);
            
            result.put("shareUrls", shareUrls);
            result.put("shortUrl", shortUrl);
            result.put("poster", poster);
            result.put("success", true);
            
        } catch (Exception e) {
            log.error("一键社交分享失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 智能批量处理
     *
     * @param imageUrls 图片URL列表
     * @param batchConfig 批量处理配置
     * @return 处理结果
     */
    public Map<String, ProcessResult> intelligentBatchProcess(List<String> imageUrls, BatchProcessConfig batchConfig) {
        try {
            return PictureBatchProcessUtils.batchProcess(imageUrls, batchConfig);
        } catch (Exception e) {
            log.error("智能批量处理失败", e);
            return new java.util.HashMap<>();
        }
    }

    /**
     * 综合统计分析
     *
     * @param pictureData 图片数据
     * @param userInteractions 用户交互数据
     * @param days 分析天数
     * @return 分析报告
     */
    public Map<String, Object> comprehensiveAnalysis(List<Map<String, Object>> pictureData, 
                                                   List<Map<String, Object>> userInteractions, 
                                                   int days) {
        Map<String, Object> report = new java.util.HashMap<>();
        
        try {
            // 用户行为分析
            UserBehaviorStats behaviorStats = PictureStatisticsUtils.analyzeUserBehavior(userInteractions);
            
            // 趋势分析
            TrendAnalysis trendAnalysis = PictureStatisticsUtils.analyzeTrend(pictureData, days);
            
            // 质量分布分析
            Map<String, Object> qualityDistribution = PictureStatisticsUtils.analyzeQualityDistribution(pictureData);
            
            // 用户偏好分析
            Map<String, Object> userPreferences = PictureStatisticsUtils.analyzeUserPreferences(userInteractions);
            
            // 热力图数据
            List<PictureHeatmapData> heatmapData = PictureStatisticsUtils.generateHeatmapData(pictureData);
            
            report.put("behaviorStats", behaviorStats);
            report.put("trendAnalysis", trendAnalysis);
            report.put("qualityDistribution", qualityDistribution);
            report.put("userPreferences", userPreferences);
            report.put("heatmapData", heatmapData);
            report.put("analysisTime", System.currentTimeMillis());
            report.put("success", true);
            
        } catch (Exception e) {
            log.error("综合统计分析失败", e);
            report.put("success", false);
            report.put("error", e.getMessage());
        }
        
        return report;
    }

    /**
     * 图片相似度检测
     *
     * @param imageUrl1 图片1 URL
     * @param imageUrl2 图片2 URL
     * @return 相似度结果
     */
    public PictureSimilarityResult detectSimilarity(String imageUrl1, String imageUrl2) {
        try {
            return PictureAnalysisUtils.calculateSimilarity(imageUrl1, imageUrl2);
        } catch (Exception e) {
            log.error("图片相似度检测失败: {} vs {}", imageUrl1, imageUrl2, e);
            return new PictureSimilarityResult();
        }
    }

    /**
     * 盗图检测
     *
     * @param originalImageUrl 原图URL
     * @param suspiciousImageUrls 疑似盗图URL列表
     * @return 检测结果
     */
    public Map<String, Boolean> detectImageTheft(String originalImageUrl, List<String> suspiciousImageUrls) {
        Map<String, Boolean> results = new java.util.HashMap<>();
        
        try {
            String originalFingerprint = PictureWatermarkUtils.generateImageFingerprint(originalImageUrl);
            
            for (String suspiciousUrl : suspiciousImageUrls) {
                boolean isTheft = PictureWatermarkUtils.detectImageTheft(originalFingerprint, suspiciousUrl);
                results.put(suspiciousUrl, isTheft);
            }
            
        } catch (Exception e) {
            log.error("盗图检测失败: {}", originalImageUrl, e);
        }
        
        return results;
    }

    /**
     * 生成图片热度排行榜
     *
     * @param pictureStats 图片统计数据
     * @param topN 前N名
     * @return 排行榜
     */
    public List<PictureStatistics> generateHotRanking(List<PictureStatistics> pictureStats, int topN) {
        try {
            return PictureStatisticsUtils.generateHeatRanking(pictureStats, topN);
        } catch (Exception e) {
            log.error("生成热度排行榜失败", e);
            return new java.util.ArrayList<>();
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 创建默认海报配置
     */
    private SharePosterConfig createDefaultPosterConfig(ShareConfig shareConfig) {
        SharePosterConfig posterConfig = new SharePosterConfig();
        posterConfig.setTitle(shareConfig.getTitle());
        posterConfig.setDescription(shareConfig.getDescription());
        posterConfig.setMainImageUrl(shareConfig.getImageUrl());
        posterConfig.setQrCodeUrl(shareConfig.getUrl());
        posterConfig.setCopyright("© 智能协同云图库");
        return posterConfig;
    }
}
